package com.elock.service.serviceImpl;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.elock.base.core.Filter;
import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.service.impl.BaseServiceImpl;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.DateUtil;
import com.elock.base.core.util.ExceptionUtil;
import com.elock.dao.TerminalTaskDao;
import com.elock.entity.SaleOrg;
import com.elock.entity.SystemDict;
import com.elock.entity.TerminalTask;
import com.elock.entity.TerminalTaskItem;
import com.elock.service.SaleOrgBaseService;
import com.elock.service.SystemDictBaseService;
import com.elock.service.TerminalTaskItemService;
import com.elock.service.TerminalTaskService;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

/**
 * 任务信息
 * 
 * @author 仁德
 */
@Service("terminalTaskServiceImpl")
public class TerminalTaskServiceImpl extends BaseServiceImpl<TerminalTask> implements TerminalTaskService {

	@Resource(name = "terminalTaskDao")
	private TerminalTaskDao terminalTaskDao;
	@Resource(name = "systemDictBaseServiceImpl")
	private SystemDictBaseService systemDictBaseService;
	@Resource(name = "saleOrgBaseServiceImpl")
	private SaleOrgBaseService saleOrgBaseService;
	@Resource(name = "terminalTaskItemServiceImpl")
	private TerminalTaskItemService terminalTaskItemService;

	// Map<String, Long> importMap = new HashMap<String, Long>();

	@Override
	@Transactional(readOnly = true)
	public Page<Map<String, Object>> findPage(Pageable pageable, Object[] args) {
		return terminalTaskDao.findPage(pageable, args);
	}

	@Override
	@Transactional(readOnly = true)
	public List<Map<String, Object>> findItemsByTaskId(String taskIds) {
		return terminalTaskDao.findItemsByTaskId(taskIds);
	}

	@Override
	@Transactional(readOnly = true)
	public String findWorkingItem(String plateNum, Integer berth, Long id) {
		return terminalTaskDao.findWorkingItem(plateNum, berth, id);
	}

	// @Override
	// @Transactional
	// public void saveUpdate(TerminalTask terminalTask) {
	//
	// Long taskId = terminalTask.getId();
	// List<TerminalTaskItem> terminalTaskItems =
	// terminalTask.getTerminalTaskItems();
	// for (Iterator<TerminalTaskItem> iterator = terminalTaskItems.iterator();
	// iterator.hasNext();) {
	// TerminalTaskItem terminalTaskItem = iterator.next();
	// String plateNum = terminalTaskItem.getPlateNum();
	// Integer berth = terminalTaskItem.getBerth();
	// if (terminalTaskItem == null || ConvertUtil.isEmpty(plateNum)) {
	// iterator.remove();
	// continue;
	// }
	// // String waybillNo = taskId == null ?
	// // terminalTaskDao.findWaybillNo(plateNum, null)
	// // : terminalTaskDao.findWaybillNo(plateNum, taskId);
	// // if (!ConvertUtil.isEmpty(waybillNo)) {
	// // ExceptionUtil.throwServiceException("车辆[" + plateNum +
	// // "]已存在未完成的运单[" + waybillNo + "]中");
	// // }
	//
	// String waybillNo = terminalTaskDao.findWorkingItem(plateNum, berth,
	// terminalTaskItem.getId());
	// if (!ConvertUtil.isEmpty(waybillNo)) {
	// ExceptionUtil.throwServiceException(
	// "车辆[" + plateNum + "]的舱位[" + berth + "]已存在于未关闭或未结束的运单[" + waybillNo +
	// "]中");
	// }
	//
	// terminalTaskItem.setTerminalTask(terminalTask);
	// if (terminalTaskItem.getToSaleOrg() != null) {
	// SaleOrg toSaleOrg =
	// saleOrgBaseService.find(terminalTaskItem.getToSaleOrg().getId());
	// terminalTaskItem.setToSaleOrg(toSaleOrg);
	// }
	// }
	// if (taskId == null) {
	// this.save(terminalTask);
	// } else {
	// this.update(terminalTask);
	// }
	// }

	@Override
	@Transactional
	public void complete(Long[] ids) {

		String idstrs = "";
		for (Long id : ids) {
			idstrs += "," + id;
		}
		idstrs = idstrs.substring(1);
		terminalTaskDao.complete(idstrs);
	}

	public String taskImport(MultipartFile multipartFile) throws Exception {

		String msg = "";
		Workbook wb = null;
		File tempFile = null;
		Cell cell = null;
		int success = 0;
		try {
			tempFile = new File(System.getProperty("java.io.tmpdir") + "/upload_" + UUID.randomUUID() + ".tmp");
			if (!tempFile.getParentFile().exists()) {
				tempFile.getParentFile().mkdirs();
			}
			multipartFile.transferTo(tempFile);
			wb = Workbook.getWorkbook(tempFile);
			Sheet sheet = wb.getSheets()[0];
			int rows = sheet.getRows();
			if (rows > 1001) {
				if (StringUtils.isNotBlank(sheet.getCell(0, 5000).getContents())) {
					ExceptionUtil.throwServiceException("一次最多导入1000条");
				} else {
					rows = 1001;
				}
			}

			String waybillNo; // 运单号
			String categoryName; // 任务类别
			String fromSaleOrgSn; // 提油机构编号
			String position; // 鹤位
			String plateNum; // 车牌号
			String berth; // 舱位
			String startTimeStr; // 出发时间
			String endTimeStr; // 预计到达时间
			String duration; // 配送时长
			String volumeStr; // 容量
			String goods; // 品名
			String quantityStr; // 数量
			String toSaleOrgSn; // 卸油机构编号
			String memo; // 备注

			List<Filter> filters = new ArrayList<Filter>();
			for (int i = 1; i < rows; i++) {
				cell = sheet.getCell(0, i);
				waybillNo = cell.getContents().trim();
				if (ConvertUtil.isEmpty(waybillNo)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "运单号未填写");
				}

				cell = sheet.getCell(1, i);
				categoryName = cell.getContents().trim();
//				if (ConvertUtil.isEmpty(categoryName)) {
//					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "任务类别未填写");
//				}
//				filters.clear();
//				filters.add(Filter.eq("code", "taskCategory"));
//				filters.add(Filter.eq("value", categoryName));
//				filters.add(Filter.isNotNull("parent"));
//				SystemDict category = systemDictBaseService.find(filters);
//				if (category == null) {
//					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "任务类[" + categoryName + "]在系统中不存在");
//				}

				cell = sheet.getCell(2, i);
				fromSaleOrgSn = cell.getContents().trim();
				if (ConvertUtil.isEmpty(fromSaleOrgSn)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "提油机构编号未填写");
				}
				filters.clear();
				filters.add(Filter.eq("sn", fromSaleOrgSn));
				SaleOrg fromSaleOrg = saleOrgBaseService.find(filters);
				if (fromSaleOrg == null) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "提油机构[" + fromSaleOrgSn + "]在系统中不存在");
				}

				cell = sheet.getCell(3, i);
				position = cell.getContents().trim();
				if (ConvertUtil.isEmpty(position)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "鹤位未填写");
				}

				cell = sheet.getCell(4, i);
				plateNum = cell.getContents().trim();
				if (ConvertUtil.isEmpty(plateNum)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "车牌号未填写");
				}

				cell = sheet.getCell(5, i);
				berth = cell.getContents().trim();
				if (ConvertUtil.isEmpty(berth)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "舱位未填写");
				}

				String taskSn = terminalTaskDao.findWorkingItem(plateNum, Integer.valueOf(berth), null);
				if (!ConvertUtil.isEmpty(taskSn)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "车牌号[" + plateNum + "]舱位[" + berth
							+ "]存在于未关闭或未结束的任务单[" + taskSn + "]中");
				}

				cell = sheet.getCell(6, i);
				startTimeStr = cell.getContents().trim();
				if (ConvertUtil.isEmpty(startTimeStr)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "出发时间未填写");
				}
				if (!isValidDate(startTimeStr)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "出发时间格式有误，格式应为yyyy-MM-dd HH:mm:ss");
				}
				Date startTime = DateUtil.convert(startTimeStr);

				cell = sheet.getCell(7, i);
				endTimeStr = cell.getContents().trim();
				if (ConvertUtil.isEmpty(endTimeStr)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "预计到达时间未填写");
				}
				if (!isValidDate(endTimeStr)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "预计到达时间格式有误，格式应为yyyy-MM-dd HH:mm:ss");
				}
				Date endTime = DateUtil.convert(endTimeStr);

				cell = sheet.getCell(8, i);
				duration = cell.getContents().trim();
				if (ConvertUtil.isEmpty(duration)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "配送时长未填写");
				}

				cell = sheet.getCell(9, i);
				volumeStr = cell.getContents().trim();
				if (ConvertUtil.isEmpty(volumeStr)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "容量未填写");
				}
				BigDecimal volume = BigDecimal.ZERO;
				try {
					volume = new BigDecimal(volumeStr);
				} catch (Exception e) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "容量格式有误");
				}

				cell = sheet.getCell(10, i);
				goods = cell.getContents().trim();
				if (ConvertUtil.isEmpty(goods)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "品名未填写");
				}

				cell = sheet.getCell(11, i);
				quantityStr = cell.getContents().trim();
				if (ConvertUtil.isEmpty(quantityStr)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "数量未填写");
				}
				BigDecimal quantity = BigDecimal.ZERO;
				try {
					quantity = new BigDecimal(quantityStr);
				} catch (Exception e) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "数量格式有误");
				}

				cell = sheet.getCell(12, i);
				toSaleOrgSn = cell.getContents().trim();
				if (ConvertUtil.isEmpty(toSaleOrgSn)) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "卸油机构未填写");
				}
				filters.clear();
				filters.add(Filter.eq("sn", toSaleOrgSn));
				SaleOrg toSaleOrg = saleOrgBaseService.find(filters);
				if (fromSaleOrg == null) {
					ExceptionUtil.throwServiceException("第" + (i + 1) + "行." + "卸油机构[" + fromSaleOrgSn + "]在系统中不存在");
				}

				cell = sheet.getCell(13, i);
				memo = cell.getContents().trim();

				TerminalTask terminalTask = new TerminalTask();

				terminalTask.setWaybillNo(waybillNo);
				terminalTask.setStatus(0);
				terminalTask.setCategory(null);
				terminalTask.setFromSaleOrg(fromSaleOrg);
				terminalTask.setPlateNum(plateNum);
				terminalTask.setStartTime(startTime);
				terminalTask.setEndTime(endTime);
				terminalTask.setDuration(duration);
				terminalTask.setVolume(volume);
				terminalTask.setGoods(goods);
				terminalTask.setQuantity(quantity);
				terminalTask.setToSaleOrg(toSaleOrg);
				terminalTask.setMemo(memo);
				 terminalTask.setPosition(Integer.valueOf(position));
				 terminalTask.setBerth(Integer.valueOf(berth));
				save(terminalTask);

				// TerminalTask terminalTask = null;
				// Long taskId = importMap.get(waybillNo);
				// if (taskId == null) {
				// terminalTask = this.saveTask(waybillNo, category,
				// fromSaleOrg);
				// importMap.put(waybillNo, terminalTask.getId());
				// } else {
				// terminalTask = this.find(taskId);
				// }
				// this.saveTaskItem(terminalTask, position, plateNum, berth,
				// startTime, endTime, duration, volume, goods,
				// quantity, toSaleOrg, memo);
			}

			int result = rows - 1;
			msg = "msg:" + "总数" + result + "行,成功导入" + success + " 行. ";
		} finally {
			// importMap.clear();
		}

		return msg;
	}

	public TerminalTask saveTask(String waybillNo, SystemDict category, SaleOrg fromSaleOrg) {

		TerminalTask terminalTask = new TerminalTask();
		terminalTask.setWaybillNo(waybillNo);
		terminalTask.setCategory(category);
		terminalTask.setFromSaleOrg(fromSaleOrg);
		this.save(terminalTask);

		return terminalTask;
	}

	public void saveTaskItem(TerminalTask terminalTask, String position, String plateNum, String berth, Date startTime,
			Date endTime, String duration, BigDecimal volume, String goods, BigDecimal quantity, SaleOrg toSaleOrg,
			String memo) {

		TerminalTaskItem terminalTaskItem = new TerminalTaskItem();
		terminalTaskItem.setTerminalTask(terminalTask);
		// terminalTaskItem.setPosition(position);
		terminalTaskItem.setPlateNum(plateNum);
		// terminalTaskItem.setBerth(berth);
		terminalTaskItem.setStartTime(startTime);
		terminalTaskItem.setEndTime(endTime);
		terminalTaskItem.setDuration(duration);
		terminalTaskItem.setVolume(volume);
		terminalTaskItem.setGoods(goods);
		terminalTaskItem.setQuantity(quantity);
		terminalTaskItem.setToSaleOrg(toSaleOrg);
		terminalTaskItem.setMemo(memo);
		terminalTaskItemService.save(terminalTaskItem);
	}

	private boolean isValidDate(String str) {
		boolean convertSuccess = true;
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			format.setLenient(false);
			format.parse(str);
		} catch (ParseException e) {
			convertSuccess = false;
		}
		return convertSuccess;
	}
}
